<template>
  <div class="app-container">
    <!-- 顶部筛选 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="3">
<!--        <el-select v-model="queryParams.deptId" placeholder="请选择科室" clearable @change="getList">-->
<!--          <el-option v-for="item in deptList" :key="item.deptId" :label="item.deptName" :value="item.deptId" />-->
<!--        </el-select>-->
      </el-col>
      <el-col :span="3">
        <el-input v-model="queryParams.doctorName" placeholder="输入医生姓名" clearable @keyup.enter="getList" />
      </el-col>
      <el-col :span="3">
        <el-date-picker v-model="queryParams.week" type="week" format="YYYY/MM/DD" placeholder="选择周" @change="getList" />
      </el-col>
      <el-col :span="2">
        <el-button type="primary" @click="getList">搜索</el-button>
      </el-col>
      <el-col :span="2">
        <el-button type="primary" @click="openAddDialog" style="margin-bottom: 12px;">新增排班</el-button>
      </el-col>
    </el-row>

    <!-- 排班表格 -->
    <el-table :data="scheduleList" border>
      <el-table-column prop="doctorName" label="医生姓名" fixed />
      <el-table-column prop="deptName" label="科室" fixed />
      <el-table-column
          v-for="(day, idx) in weekDays"
          :key="day.date"
          :label="day.label"
          align="center"
      >
        <template #default="scope">
          <div @click="openDetail(scope.row, day.date)" style="cursor:pointer;">
            <div>上午: <span :style="{color: getColor(scope.row, day.date, 'am')}">{{ getCellText(scope.row, day.date, 'am') }}</span></div>
            <div>下午: <span :style="{color: getColor(scope.row, day.date, 'pm')}">{{ getCellText(scope.row, day.date, 'pm') }}</span></div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="80" align="center">
        <template #default="scope">
          <el-button icon="Setting" size="small" @click="openDetail(scope.row, weekDays[0].date)">设置</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        v-show="total>0"
        :total="total"
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        @current-change="getList"
        @size-change="getList"
    />

    <!-- 排班详情弹窗 -->
    <el-dialog v-model="detailOpen" width="900px" title="医生排班详情">
      <div class="schedule-detail-dialog" style="display:flex;">
        <div class="left-panel" style="width:260px;background:#ff9800;color:#fff;padding:24px 16px;">
          <h3 style="margin-bottom:12px;">{{ detailInfo.doctorName }}医生排班详情</h3>
          <div style="font-size:18px;margin-bottom:12px;">{{ detailInfo.dateLabel }}</div>
          <div style="margin-bottom:16px;">
            <div style="font-weight:bold;">上午</div>
            <div>接诊时间: {{ detailInfo.amTime }}</div>
            <div>号源数: {{ detailInfo.amNum }}</div>
            <div>接诊人数: {{ detailInfo.amVisited }}</div>
            <el-button size="small" @click="closeSchedule('am')">关闭预约</el-button>
          </div>
          <div>
            <div style="font-weight:bold;">下午</div>
            <div>接诊时间: {{ detailInfo.pmTime }}</div>
            <div>号源数: {{ detailInfo.pmNum }}</div>
            <div>接诊人数: {{ detailInfo.pmVisited }}</div>
            <el-button size="small" @click="closeSchedule('pm')">关闭预约</el-button>
          </div>
        </div>
        <div class="right-panel" style="flex:1;padding:24px;">
          <el-form :model="detailInfo" label-width="100px">
            <el-form-item label="上午状态">
              <el-select v-model="detailInfo.amStatus" placeholder="请选择">
                <el-option label="排班" value="排班" />
                <el-option label="休息" value="休息" />
              </el-select>
            </el-form-item>
            <el-form-item label="上午号源">
              <el-input-number v-model="detailInfo.amNum" :min="0" :disabled="detailInfo.amStatus !== '排班'" />
            </el-form-item>
            <el-form-item label="上午接诊人数">
              <el-input-number v-model="detailInfo.amVisited" :min="0" :disabled="detailInfo.amStatus !== '排班'" />
            </el-form-item>
            <el-form-item label="下午状态">
              <el-select v-model="detailInfo.pmStatus" placeholder="请选择">
                <el-option label="排班" value="排班" />
                <el-option label="休息" value="休息" />
              </el-select>
            </el-form-item>
            <el-form-item label="下午号源">
              <el-input-number v-model="detailInfo.pmNum" :min="0" :disabled="detailInfo.pmStatus !== '排班'" />
            </el-form-item>
            <el-form-item label="下午接诊人数">
              <el-input-number v-model="detailInfo.pmVisited" :min="0" :disabled="detailInfo.pmStatus !== '排班'" />
            </el-form-item>
          </el-form>
          <el-button type="primary" @click="setSchedule">设置排班</el-button>
        </div>
      </div>
      <template #footer>
        <el-button @click="detailOpen = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 新增排班弹窗 -->
    <el-dialog v-model="addDialogOpen" title="新增排班" width="600px">
      <el-form :model="addForm" label-width="100px" :rules="addRules" ref="addFormRef">
        <el-form-item label="医生" prop="doctorId">
          <el-select v-model="addForm.doctorId" placeholder="请选择医生" filterable>
            <el-option v-for="item in doctorList" :key="item.doctorId" :label="item.doctorName" :value="item.doctorId" />
          </el-select>
        </el-form-item>
        <el-form-item label="日期" prop="scheduleDate">
          <el-date-picker v-model="addForm.scheduleDate" type="date" placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="上午状态" prop="amStatus">
          <el-select v-model="addForm.amStatus" placeholder="请选择">
            <el-option label="排班" value="排班" />
            <el-option label="休息" value="休息" />
          </el-select>
        </el-form-item>
        <el-form-item label="上午号源" v-if="addForm.amStatus==='排班'">
          <el-input-number v-model="addForm.amNum" :min="0" />
        </el-form-item>
        <el-form-item label="下午状态" prop="pmStatus">
          <el-select v-model="addForm.pmStatus" placeholder="请选择">
            <el-option label="排班" value="排班" />
            <el-option label="休息" value="休息" />
          </el-select>
        </el-form-item>
        <el-form-item label="下午号源" v-if="addForm.pmStatus==='排班'">
          <el-input-number v-model="addForm.pmNum" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogOpen=false">取消</el-button>
        <el-button type="primary" @click="submitAdd">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { listDoctorSchedule, getDoctorScheduleDetail, setDoctorSchedule, closeDoctorSchedule, listDoctor, listDepartment, addDoctorSchedule } from '@/api/system/doctorschedule'
import dayjs from 'dayjs'

const queryParams = reactive({
  deptId: null,
  doctorName: '',
  week: new Date(),
  pageNum: 1,
  pageSize: 10
})
const deptList = ref([])
const scheduleList = ref([])
const weekDays = ref([])
const total = ref(0)
const detailOpen = ref(false)
const detailInfo = reactive({
  doctorId: '',
  scheduleDate: '',
  dateLabel: '',
  amStatus: '休息',
  amNum: 0,
  amVisited: 0,
  pmStatus: '休息',
  pmNum: 0,
  pmVisited: 0,
  doctorName: '',
  deptName: ''
})
const calendarDate = ref(new Date())

// 新增排班相关
const addDialogOpen = ref(false)
const addForm = reactive({
  doctorId: '',
  scheduleDate: '',
  amStatus: '休息',
  amNum: 0,
  pmStatus: '休息',
  pmNum: 0
})
const addFormRef = ref(null)
const addRules = {
  doctorId: [{ required: true, message: '请选择医生', trigger: 'change' }],
  scheduleDate: [{ required: true, message: '请选择日期', trigger: 'change' }],
  amStatus: [{ required: true, message: '请选择上午状态', trigger: 'change' }],
  pmStatus: [{ required: true, message: '请选择下午状态', trigger: 'change' }]
}
const doctorList = ref([])

function getWeekDays(date) {
  // 返回本周每天的日期和label
  const start = dayjs(date).startOf('week').add(1, 'day') // 周一
  return Array.from({length: 7}).map((_, i) => {
    const d = start.add(i, 'day')
    return {
      date: d.format('YYYY-MM-DD'),
      label: d.format('YYYY/MM/DD dddd')
    }
  })
}

function getList() {
  weekDays.value = getWeekDays(queryParams.week)
  const params = {
    ...queryParams,
    startDate
        : weekDays.value[0].date,
    endDate: weekDays.value[6].date
  }
  listDoctorSchedule(params).then(res => {
    scheduleList.value = res.rows
    total.value = res.total
  })
}

function getCellText(row, date, period) {
  const schedule = row.schedules?.find(
      s => dayjs(s.scheduleDate).format('YYYY-MM-DD') === date
  )
  if (!schedule) return '休'
  if (period === 'am') {
    if (schedule.amStatus === '排班') return `${schedule.amNum}/${schedule.amVisited}`
    if (schedule.amStatus) return schedule.amStatus
    return '休'
  }
  if (period === 'pm') {
    if (schedule.pmStatus === '排班') return `${schedule.pmNum}/${schedule.pmVisited}`
    if (schedule.pmStatus) return schedule.pmStatus
    return '休'
  }
  return ''
}

function getColor(row, date, period) {
  const schedule = row.schedules?.find(
      s => dayjs(s.scheduleDate).format('YYYY-MM-DD') === date
  )
  if (!schedule) return '#999'
  if ((period === 'am' && schedule.amStatus !== '排班') || (period === 'pm' && schedule.pmStatus !== '排班')) return 'red'
  return '#222'
}

function openDetail(row, date) {
  getDoctorScheduleDetail(row.doctorId, date).then(res => {
    if (!res.data || Object.keys(res.data).length === 0) {
      // 没有排班数据，初始化为休息
      Object.assign(detailInfo, {
        doctorId: row.doctorId,
        scheduleDate: date,
        dateLabel: dayjs(date).format('YYYY年MM月DD日 dddd'),
        amStatus: '休息',
        amNum: 0,
        amVisited: 0,
        pmStatus: '休息',
        pmNum: 0,
        pmVisited: 0,
        doctorName: row.doctorName,
        deptName: row.deptName
      })
    } else {
      Object.assign(detailInfo, res.data, {
        doctorId: row.doctorId,
        scheduleDate: date,
        dateLabel: dayjs(date).format('YYYY年MM月DD日 dddd'),
        doctorName: row.doctorName,
        deptName: row.deptName
      })
      // 如果后端返回的 amStatus/pmStatus 为空，也初始化为休息
      if (!detailInfo.amStatus) detailInfo.amStatus = '休息'
      if (!detailInfo.pmStatus) detailInfo.pmStatus = '休息'
    }
    detailOpen.value = true
  })
}
function setSchedule() {
  setDoctorSchedule(detailInfo).then(() => {
    getList()
    detailOpen.value = false
  })
}
function closeSchedule(period) {
  closeDoctorSchedule({
    doctorId: detailInfo.doctorId,
    scheduleDate: detailInfo.scheduleDate,
    period
  }).then(() => {
    getList()
    detailOpen.value = false
  })
}

function openAddDialog() {
  addForm.doctorId = ''
  addForm.scheduleDate = ''
  addForm.amStatus = '休息'
  addForm.amNum = 0
  addForm.pmStatus = '休息'
  addForm.pmNum = 0
  addDialogOpen.value = true
}

function submitAdd() {
  addFormRef.value.validate(valid => {
    if (!valid) return
    addDoctorSchedule(addForm).then(() => {
      addDialogOpen.value = false
      getList()
    })
  })
}

onMounted(() => {
  listDepartment().then(res => {
    deptList.value = res.rows
  })
  listDoctor().then(res => {
    doctorList.value = res.rows
  })
  getList()
})
</script>